﻿package idv.cjcat.arrowwalker.components {
	import com.pblabs.engine.components.TickedComponent;
	import com.pblabs.engine.core.InputKey;
	import com.pblabs.engine.core.InputManager;
	import com.pblabs.engine.core.InputMap;
	import flash.geom.Point;
	import flash.utils.Dictionary;
	import idv.cjcat.arrowwalker.ArrowWalker;
	
	public class SimpleController extends TickedComponent {
		
		public static const UP:String = "up";
		public static const DOWN:String = "down";
		public static const LEFT:String = "left";
		public static const RIGHT:String = "right";
		
		public var speed:Number;
		
		private const RADIAN_TO_DEGREE:Number = 57.2957;
		
		private var _keyMap:Dictionary;
		private var _inputMap:InputMap;
		
		public function SimpleController(speed:Number = 300) {
			this.speed = speed;
		}
		
		override public function onTick(tickRate:Number):void {
			var dx:Number = 0;
			var dy:Number = 0;
			
			//handle vertical displacement
			if (_keyMap[UP]) dy -= speed;
			if (_keyMap[DOWN]) dy += speed;
			
			//handle horizontal displacement
			if (_keyMap[LEFT]) dx -= speed;
			if (_keyMap[RIGHT]) dx += speed;
			
			
			if (dx & dy) {
				dx *= Math.SQRT1_2;
				dy *= Math.SQRT1_2;
			}
			
			//time alignment
			dx *= tickRate;
			dy *= tickRate;
			
			//get position
			var position:Point = owner.getProperty(ArrowWalker.POSITION_REF) as Point;
			
			//set position & rotation
			position.x += dx;
			position.y += dy;
			if (position.x > 320) position.x = 320;
			else if (position.x < -320) position.x = -320;
			if (position.y > 240) position.y = 240;
			else if (position.y < -240) position.y = -240;
			owner.setProperty(ArrowWalker.POSITION_REF, position);
			if (dx | dy) owner.setProperty(ArrowWalker.ROTATION_REF, RADIAN_TO_DEGREE * Math.atan2(dx, -dy));
		}
		
		override protected function onAdd():void {
			super.onAdd();
			
			_keyMap = new Dictionary();
			
			_inputMap = new InputMap();
			
			//key-to-action mappings
			_inputMap.mapKeyToAction(InputKey.UP, UP);
			_inputMap.mapKeyToAction(InputKey.DOWN, DOWN);
			_inputMap.mapKeyToAction(InputKey.LEFT, LEFT);
			_inputMap.mapKeyToAction(InputKey.RIGHT, RIGHT);
			
			//action-to-handler mappings
			_inputMap.mapActionToHandler(UP, onUp);
			_inputMap.mapActionToHandler(DOWN, onDown);
			_inputMap.mapActionToHandler(LEFT, onLeft);
			_inputMap.mapActionToHandler(RIGHT, onRight);
		}
		
		override protected function onRemove():void {
			super.onRemove();
			_keyMap = null;
		}
		
		protected function onUp(value:Number):void {
			_keyMap[UP] = value;
		}
		
		protected function onDown(value:Number):void {
			_keyMap[DOWN] = value;
		}
		
		protected function onLeft(value:Number):void {
			_keyMap[LEFT] = value;
		}
		
		protected function onRight(value:Number):void {
			_keyMap[RIGHT] = value;
		}
	}
}